#include "QNBHeartThread.h"

#include <QDebug>
#include <QMessageBox>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonValue>
#include <QDir>
#include <QFileInfo>


#include "QNBConstant.h"
#include "QNBConfig.h"
#include "QNBUserInfo.h"

QNBHeartThread::QNBHeartThread()
{
    m_heartTimer = new QTimer();
    m_updateConfigTimer = new QTimer();
    m_deleteUserDataTimer = new QTimer();

    reqHeartNAM = new QNetworkAccessManager(this);
    connect(reqHeartNAM,SIGNAL(finished(QNetworkReply*)),SLOT(replyHeartFinished(QNetworkReply*)));

    reqUpdateConfigNAM = new QNetworkAccessManager(this);
    connect(reqUpdateConfigNAM,SIGNAL(finished(QNetworkReply*)),SLOT(replyUpdateConfigFinished(QNetworkReply*)));

    connect(m_deleteUserDataTimer, SIGNAL(timeout()), this, SLOT(userdataDelete()));

    reply = NULL;
    reply2 = NULL;
}

QNBHeartThread::~QNBHeartThread()
{
    m_heartTimer->stop();
    delete m_heartTimer;

    m_updateConfigTimer->stop();
    delete m_updateConfigTimer;

    m_deleteUserDataTimer->stop();
    delete m_deleteUserDataTimer;


    if(reply) {
        delete reply;
    }

    if(reply2) {
        delete reply2;
    }

    delete reqHeartNAM;
    delete reqUpdateConfigNAM;
}

void QNBHeartThread::setTimer()
{
    m_heartTimer->stop();
    m_updateConfigTimer->stop();

    m_heartTimer->setInterval(QNBConfig::getInstance()->heartInterval() * 1000);
    m_updateConfigTimer->setInterval(QNBConfig::getInstance()->updateConfigInterval() * 1000);
//    m_deleteUserDataTimer->setInterval(QNBConfig::getInstance()->deleteUserDataDelayTime());

    disconnect(m_heartTimer, 0, 0, 0);
    disconnect(m_updateConfigTimer, 0, 0, 0);

    connect(m_heartTimer, SIGNAL(timeout()), this, SLOT(reqHeart()));
    connect(m_updateConfigTimer, SIGNAL(timeout()), this, SLOT(reqUpdateConfig()));

    m_heartTimer->start();
    m_updateConfigTimer->start();

    qDebug()<<"setTimer....";
}

void QNBHeartThread::reqHeart()
{
    if (QNBUserInfo::getInstance()->mstrIdentify.isEmpty() || QNBUserInfo::getInstance()->mstrClientId.isEmpty()) {
        qDebug()<<"reqHeart, identify or Clientid is empty, req heart failed.";
        return;
    }

    if (QNBUserInfo::getInstance()->mLoginStatus != ENUM_LOGIN) {
        qDebug()<<"reqHeart, not login.";
        return;
    }

    QString strUrl = QNBConfig::getInstance()->getServerHttpController()+"/heart.html?identify="+QNBUserInfo::getInstance()->mstrIdentify+"&clientid="+QNBUserInfo::getInstance()->mstrClientId;
    QNetworkRequest req(strUrl);

    if(reply != NULL) {
        disconnect(reply, 0, 0, 0);
        delete reply;
    }
    reply = reqHeartNAM->get(req);

    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(reqError(QNetworkReply::NetworkError)));


    int sec = this->m_heartTimer->interval()/1000;
    if (sec != QNBConfig::getInstance()->heartInterval() && QNBConfig::getInstance()->heartInterval() > 0) {
        m_heartTimer->stop();
        m_heartTimer->setInterval(QNBConfig::getInstance()->heartInterval()*1000);
        m_heartTimer->start();
    }
    qDebug()<<"heart....";
}

void QNBHeartThread::reqUpdateConfig()
{
    if (QNBUserInfo::getInstance()->mstrClientId.isEmpty()) {
        qDebug()<<"Clientid is empty, update Config failed.";
        return;
    }

    QString strUrl = QNBConfig::getInstance()->getServerHttpController()+"/getconfig.html?clientid="+QNBUserInfo::getInstance()->mstrClientId;
    QNetworkRequest req(strUrl);

    if(reply2 != NULL) {
        disconnect(reply2, 0, 0, 0);\
        delete reply2;
    }
    reply2 = reqUpdateConfigNAM->get(req);

    connect(reply2, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(reqError(QNetworkReply::NetworkError)));

    //reply2->deleteLater();
    qDebug()<<"update Config....";

    int sec = this->m_updateConfigTimer->interval()/1000;
    if (sec != QNBConfig::getInstance()->updateConfigInterval() && QNBConfig::getInstance()->updateConfigInterval() > 0) {
        m_updateConfigTimer->stop();
        m_updateConfigTimer->setInterval(QNBConfig::getInstance()->updateConfigInterval()*1000);
        m_updateConfigTimer->start();
    }
}

void QNBHeartThread::replyHeartFinished(QNetworkReply *reply)
{
    if(reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<"no error.....";
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串

        qDebug() << "replyFinished:  " <<result;

        if(!bytes.isEmpty()) {
            QJsonParseError json_error;
            QJsonDocument parse_doucment = QJsonDocument::fromJson(bytes, &json_error);
            if(json_error.error == QJsonParseError::NoError)
            {
                if(parse_doucment.isObject())
                {
                    QJsonObject obj = parse_doucment.object();
                    QString strActionValue = QNBUtls::getStringValue(obj, "action_exit", "0");
                    if(!strActionValue.isEmpty())
                    {
                        if (strActionValue.toInt() == 1) {
                            qDebug() << "do exit!!!";

                            //登出标志，
                            QNBUserInfo::getInstance()->mForceAction = ENUM_FORCE_LOGOUT;
                        }

                        //刷新下最近心跳时间
                        QNBUserInfo::getInstance()->miHeartTime = QNBUtls::curTime();
                    }
                }
            }
        }
    } else {
        qDebug() << "replyFinished:  " << reply->error() << " " <<reply->errorString();

//        QMessageBox msgBox;
//        msgBox.setText(tr("the auth photo is not exist?"));
//        msgBox.exec();
    }

    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<status_code;
}

void QNBHeartThread::reqError(QNetworkReply::NetworkError errorCode)
{
    qDebug() << "reqLoginError  errorCode: " << (int)errorCode;


}

void QNBHeartThread::replyUpdateConfigFinished(QNetworkReply *reply)
{
    /* {"historydatasavetime":"66",
     * "submitphotointerval":"56",
     * "lockscreenjudgetime":"6",
     * "logoutdelelestatus":"1"} */
    if(reply->error() == QNetworkReply::NoError)
    {
        qDebug()<<"no error.....";
        QByteArray bytes = reply->readAll();  //获取字节
        QString result(bytes);  //转化为字符串

        qDebug() << "replyFinished:  " <<result;
        QJsonParseError json_error;
        QJsonDocument parse_doucment = QJsonDocument::fromJson(bytes, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            if(parse_doucment.isObject())
            {
                bool bChange = false;
                QJsonObject obj = parse_doucment.object();
                QString strHeartInterval = QNBUtls::getStringValue(obj, "submitphotointerval", ""+SUBMIT_PHOTO_INTERVAL);
                if(!strHeartInterval.isEmpty()) {
                    if(QNBConfig::getInstance()->setSubmitPhotoInterval(strHeartInterval.toInt())) {
                        bChange = true;
                    }
                }

                QString strLockscreenJudgeMaxCount = QNBUtls::getStringValue(obj, "lockscreenjudgetime", ""+LOCKSCREEN_JUDGE_MAX_COUNT);
                if(!strLockscreenJudgeMaxCount.isEmpty()) {
                    if(QNBConfig::getInstance()->setLockscreenJudgeMaxCount(strLockscreenJudgeMaxCount.toInt())) {
                        bChange = true;
                    }
                }


                QString strValue = QNBUtls::getStringValue(obj, "checkphotointerval", ""+HEART_INTERVAL);
                if(!strValue.isEmpty()) {
                    if(QNBConfig::getInstance()->setHeartInterval(strValue.toInt())) {
                        bChange = true;
                    }

                }

                strValue = QNBUtls::getStringValue(obj, "heartinterval", ""+HEART_INTERVAL);
                if(!strValue.isEmpty()) {
                    if(QNBConfig::getInstance()->setLockscreenJudgeMaxCount(strValue.toInt())) {
                        bChange = true;
                    }
                }

                strValue = QNBUtls::getStringValue(obj, "updateconfiginterval", ""+UPDATE_CONFIG_INTERVAL);
                if(!strValue.isEmpty()) {
                    if(QNBConfig::getInstance()->setUpdateConfigInterval(strValue.toInt())) {
                        bChange = true;
                    }
                }

                strValue = QNBUtls::getStringValue(obj, "submitphotointerval", ""+SUBMIT_PHOTO_INTERVAL);
                if(!strValue.isEmpty()) {
                    if(QNBConfig::getInstance()->setSubmitPhotoInterval(strValue.toInt())) {
                        bChange = true;
                    }
                }

                strValue = QNBUtls::getStringValue(obj, "lockscreenjudgetime", ""+LOCKSCREEN_JUDGE_MAX_COUNT);
                if(!strValue.isEmpty()) {
                    if(QNBConfig::getInstance()->setLockscreenJudgeMaxCount(strValue.toInt())) {
                        bChange = true;
                    }
                }


                if (bChange) {
                    QNBConfig::getInstance()->saveConfg();
                }
                //other params update? todo...
            }
        }
    } else {
        qDebug() << "replyFinished:  " << reply->error() << " " <<reply->errorString();
    }

    QVariant status_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    qDebug()<<status_code;
}

void QNBHeartThread::chakan(QString path, time_t deleteTime)
{
  QDir dir(path);

  foreach(QFileInfo mfi ,dir.entryInfoList())
  {
    if(mfi.isFile()) {
        int modifyTime = mfi.lastModified().toTime_t();
        if (modifyTime < deleteTime) {

            qDebug()<< "File: " << mfi.fileName()<<" remove!";
            QFile::remove(mfi.absoluteFilePath());
        }
    } else if (mfi.isDir()) {
        if(mfi.fileName()=="." || mfi.fileName() == "..")continue;
        qDebug() << "Entry Dir : " << mfi.absoluteFilePath();
        chakan(mfi.absoluteFilePath(), deleteTime);
    }
  }
}

void QNBHeartThread::userdataDelete()
{
    time_t deleteTime = QDateTime::currentDateTime().toTime_t();
    deleteTime -= QNBConfig::getInstance()->deleteUserDataDelayTime();;

    chakan(TMP_DATA_DIR, deleteTime);

    //2 days before
    chakan(AUTH_DATA_DIR, QDateTime::currentDateTime().toTime_t() - 60*60*24*2);
}

